<template>
	<view class="my-select">
		<xDataSelect ref='xSelect' v-model="selected" :options="props.options" v-bind='attrs'
			:searchable="typeof props.api== 'boolean'?props.api:true"
			:remote="typeof props.api== 'boolean'?props.api:true" :multiple="props.multiple"
			:clearable='props.clearable' :placeholder="props.placeholder" @change="changeVal" @load-data='onLoadData'
			:loadSelected='!$System.isEmpty(props.initParams)' @loadSelected='onloadSelected' />
	</view>
</template>

<script setup>
	import {
		ref,
		watch,
		computed,
		useAttrs,
		nextTick
	} from 'vue'
	import {
		onLoad,
		onReady,
		onShow
	} from '@dcloudio/uni-app'
	import xDataSelect from '@/uni_modules/x-data-select/components/x-data-select/x-data-select.vue'
	import {
		debounce,
		strToArr
	} from '@/common/common.js'
	const attrs = useAttrs()

	const props = defineProps({
		// 选中值
		modelValue: {
			type: [String, Number, Object],
			default: null
		},
		// 占位符
		placeholder: {
			type: String,
			default: '请选择'
		},
		// 选项数据
		options: {
			type: Array,
			default: () => []
		},
		// 是否可清除
		clearable: {
			type: Boolean,
			default: false
		},
		// 是否可搜索
		searchable: {
			type: Boolean,
			default: false
		},
		// 是否远程搜索
		remote: {
			type: Boolean,
			default: false
		},
		// 远程检索接口
		api: {
			type: Function || Boolean,
			required: false,
			default: false
		},
		responseAdapter: {
			type: Function,
			default: (res) => ({
				...res,
				data: res.data,
				total: res.total,
			}),
		},
		// 初始化参数，为回显时使用
		initParams: {
			type: Object,
			default: () => ({}),
		},
		queryParams: {
			type: Object,
			default: () => ({}),
		},
		queryParamKey: {
			type: String,
			default: 'keyword',
		},
		// 是否从接口加载选中值
		loadSelected: {
			type: Boolean,
			default: false
		},
		// 标签键名
		labelKey: {
			type: String,
			default: 'name'
		},
		// 值键名
		valueKey: {
			type: String,
			default: 'id'
		},
		// 是否多选
		multiple: {
			type: Boolean,
			default: false
		}
	})

	const emit = defineEmits(['update:modelValue', 'change'])
	const selected = computed({
		get: () => props.modelValue,
		set: (val) => emit('update:modelValue', val)
	})

	const changeVal = (val) => {
		emit('change', val)
	}

	// 获取数据
	const debouncedGetOptions = debounce(async (query, callback) => {
		try {
			let rawRes = await props.api({
				...query
			})
			const {
				data
			} = props.responseAdapter(rawRes)
			let labelFieldArr = strToArr(props.labelKey)
			// console.log('data.map====>', data);
			let resData = data.map(item => {
				return {
					...item,
					value: item[props.valueKey],
					label: labelFieldArr
						.map((field) => item[field])
						.toString()
						.replace(/,/g, '-'),
				}
			})
			callback(resData)
		} catch (error) {
			console.error('获取选项数据失败:', error)
			callback([]) // 返回空数组
		}
	}, 500)

	// 加载数据
	const onLoadData = ({
		keyword,
		page,
		pageSize,
		isSearch,
		callback
	}) => {
		// 远程加载数据
		let params = {
			...props.queryParams,
			pageNo: page,
			pageSize
		}
		params[props.queryParamKey] = keyword
		debouncedGetOptions(params, callback)
	}
	const initData = computed(() => {
		return props.initParams
	})
	// 初始化显示数据
	const onloadSelected = ({
		value,
		callback
	}) => {
		// 远程加载数据
		let params = {
			...initData.value,
		}
		debouncedGetOptions(params, callback)
	}

	const xSelect = ref(null)

	watch(() => props.queryParams, () => {
		nextTick(() => {
			xSelect.value.initOptions()
		})
	}, {
		deep: true
	})

	onLoad((opt) => {})
	onShow(() => {})

	defineExpose({
		xSelect
	})
</script>

<style>
	.my-select {
		width: 100%;
	}
</style>